#include "httpgetweather.h"
#include "ui_httpgetweather.h"
#include <QDebug>
#include <QJsonObject>
#include <QJsonArray>
#include <QJsonValue>
#include <QJsonDocument>
#include <QJsonParseError>

HttpGetWeather::HttpGetWeather(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::HttpGetWeather)
{
    ui->setupUi(this);

    connect(&manager,&QNetworkAccessManager::finished,this,&HttpGetWeather::read_data);
}

HttpGetWeather::~HttpGetWeather()
{
    delete ui;
}

void HttpGetWeather::read_data(QNetworkReply *reply)
{
    QString data = reply->readAll();
    qDebug()<<data;

    //json解析  -- QJson
    QJsonParseError err;
    QJsonDocument doc = QJsonDocument::fromJson(data.toUtf8(),&err);
    if(err.error != QJsonParseError::NoError)  //检查是否是json格式
    {
        qDebug()<<"json error!";
    }

    QJsonObject obj = doc.object();

    QJsonObject dataObj = obj.value("data").toObject();

    QJsonArray forecastArray = dataObj.value("forecast").toArray();

    //获取数组长度--- 取到数组中的第一个对象
    qDebug()<<forecastArray.size();
    if(forecastArray.size() > 0)
    {
        QJsonObject forecastArrayObj = forecastArray.at(0).toObject();
        QString high = forecastArrayObj.value("high").toString();
        QString low = forecastArrayObj.value("low").toString();
        QString notice = forecastArrayObj.value("notice").toString();

        ui->highLb->setText(high);
        ui->lowLb->setText(low);
        ui->noticeLb->setText(notice);
    }
}

void HttpGetWeather::on_pushButton_clicked()
{
    //发送请求
    QUrl url(QString("http://t.weather.sojson.com/api/weather/city/%1").arg("101100714"));
    //QUrl url(QString("http://t.weather.sojson.com/api/weather/city/%1").arg("101280101"));
    QNetworkRequest request(url);
    manager.get(request);
}
